package com.tg.app.activity.device.add;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tg.app.R;
import com.tg.app.adapter.ApDeviceAdapter;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGWifiUtil;
import com.tg.appcommon.android.WifiBroadcastReceiver;
import com.tg.appcommon.android.WifiBroadcastReceiverHelper;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the  factory method to
 * create an instance of this fragment.
 */
public class AddSearchDeviceFragment extends Fragment implements View.OnClickListener {

    private WifiBroadcastReceiverHelper mWifiBroadcastReceiverHelper = new WifiBroadcastReceiverHelper();
    private RecyclerView recyclerView;
    private ApDeviceAdapter apDeviceAdapter;
    private List<ScanResult> wifiApList = new ArrayList<>();
    private ImageView imageView;
    private int count;
    private final static int GET_WIFI_LIST = 3;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                if (count < 15) {
                    startScan();
                    getWifiList();
                    handler.sendEmptyMessageDelayed(0, 3000);
                } else if (wifiApList.size() == 0) {
                    deviceNoFound();
                }
                count++;
            }else if(msg.what == GET_WIFI_LIST){
                if (wifiApList.size()>0){
                    recyclerView.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.GONE);
                }else  {
                    recyclerView.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                }
                apDeviceAdapter.notifyDataSetChanged();
            }
        }
    };
    private OnAddDeviceListener listener;
    public AddSearchDeviceFragment() {
        // Required empty public constructor
    }

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        apDeviceAdapter = new ApDeviceAdapter(wifiApList, position -> {

            if (wifiApList.size()>position){
                ScanResult ap = wifiApList.get(position);
                String ssid = ap.SSID.replace(ApScanConfiguration.INSTANCE.apNamePrefix() + "_","");
                listener.onDeviceConnecting(ssid, AddFragmentTabActivity.TYPE_SCAN_QRCODE);
            }



        });
        recyclerView.setAdapter(apDeviceAdapter);
        tipsDialog();
        //Glide.with(this).asGif().load(R.mipmap.search_ok).into(imageView);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_add_search_device, container, false);
        recyclerView = view.findViewById(R.id.device_add_ap_camera_list);
        view.findViewById(R.id.add_device_research).setOnClickListener(this);
        view.findViewById(R.id.tv_add_device_no_found).setOnClickListener(this);
        imageView = view.findViewById(R.id.icon_device_ap_add_search);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(container.getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);


        return view;

    }

    private void getWifiList() {
        Context context = getContext();
        if (context == null) return;
        List<ScanResult> scanResults = TGWifiUtil.noSameName(TGWifiUtil.getWifiScanResult(context));
        wifiApList.clear();

        for (ScanResult result : scanResults) {
            if (!TextUtils.isEmpty(result.SSID) && result.SSID.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix()) && !wifiApList.contains(result)) {
                wifiApList.add(result);
            }
        }
        Collections.sort(wifiApList, new Comparator<ScanResult>() {
            @Override
            public int compare(ScanResult o1, ScanResult o2) {
                return o1.SSID.compareTo(o2.SSID);
            }
        });
        handler.sendEmptyMessageDelayed(GET_WIFI_LIST, 1000);
    }

    @Override
    public void onResume() {
        super.onResume();
        mWifiBroadcastReceiverHelper.registerReceiver(getActivity());
        mWifiBroadcastReceiverHelper.setReceiverListener(new WifiBroadcastReceiver.WifiBroadcastReceiverListener() {
            @Override
            public void onWifiListChanged() {
                wifiListChanged();
            }

            @Override
            public void onWifiConnected() {
                wifiConnected();
            }

            @Override
            public void onUnavailable() {
            }
        });
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onPause() {
        super.onPause();
        mWifiBroadcastReceiverHelper.unregisterReceiver(getActivity());
    }

    private void startScan() {

        WifiManager mWifiManager = (WifiManager) TGApplicationBase.getApplication().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.startScan();
        }

    }

    private void wifiListChanged() {
        getWifiList();
    }

    private void wifiConnected() {
        getWifiList();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.add_device_research) {
        } else if (id == R.id.tv_add_device_no_found) {
            deviceNoFound();
        }
    }

    private void tipsDialog() {
        Context context = getContext();
        if (context == null) return;
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_search_device, null);
        TextView textView = view.findViewById(R.id.text_search_deivce_tip);
        if (textView != null){
            textView.setText(R.string.dialog_search_deivce_tips2);
        }

        final Dialog mDialog = new Dialog(context, com.module.appcommon.R.style.alert_dialog);
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
        view.findViewById(R.id.btn_dialog_search_device).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    private void deviceNoFound() {
        Context context = getContext();
        if (context == null) return;
        handler.removeCallbacksAndMessages(null);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_search_device_settings, null);
        TextView title = view.findViewById(R.id.deivce_settings_title_mark);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            title.setText(Html.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix())));
        } else {
            title.setText(HtmlCompat.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix()), HtmlCompat.FROM_HTML_MODE_LEGACY));
        }
        final Dialog mDialog = new Dialog(context, com.module.appcommon.R.style.alert_dialog);
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
        view.findViewById(R.id.btn_dialog_search_settings_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                count = 0;
                handler.sendEmptyMessage(0);
            }
        });
        view.findViewById(R.id.btn_dialog_search_settings_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count = 0;
                mDialog.dismiss();
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

            }
        });
    }
}